﻿using System;
using System.Text;
using System.Xml.Linq;

namespace Redbrick.Silverlight.Common
{
	public static partial class Conversion
	{

		public static int ToInt(this bool b)
		{
			if (b) return 1;
			return 0;
		}

		public static bool ToBool<_type>(this _type n)
		{
			return Convert.ToBoolean(n);
		}


		/// <summary>
		/// convert a string to a double
		/// </summary>
		public static double ToDouble(this string str)
		{
			double dbl = double.NaN;
			if (!double.TryParse(str, out dbl))
				throw new ArgumentException("'" + str + "' is not a valid double");
			return dbl;
		}
		
		/// <summary>
		/// convert an XElement value to a double
		/// </summary>
		public static double ToDouble(this XElement xel)
		{

			double dbl = double.NaN;
			if (string.IsNullOrEmpty(xel.Value) || !double.TryParse(xel.Value, out dbl))
			{
				throw new ArgumentException("'" + xel.Value + "' is not a valid double");
			}
			return dbl;
		}
	
		/// <summary>
		/// convert a byte[] to a hex string
		/// </summary>
		public static string ToHexString(this byte[] data)
		{
			int len = data.Length;
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < len; i++)
			{
				sb.Append(data[i].ToString("X2"));
			}

			return sb.ToString();
		}

		/// <summary>
		/// convert a string to a UTF8 byte array
		/// </summary>
		public static byte[] ToByteArray(this string str)
		{
			UTF8Encoding encoding = new UTF8Encoding();
			byte[] data = encoding.GetBytes(str.Trim());
			return data;
		}

		/// <summary>
		/// convert an array of bytes to a unicode string
		/// </summary>
		public static string ToUnicodeString(this byte[] bites)
		{
			return System.Text.Encoding.Unicode.GetString(bites, 0, bites.Length);
		}

		/// <summary>
		/// convert an array of bytes to a UTF8 string
		/// </summary>
		public static string ToUTF8String(this byte[] bites)
		{
			bites = bites.TrimEnd();
			return System.Text.Encoding.UTF8.GetString(bites, 0, bites.Length);
		}


	}
}
